package pl.streamsoft.currencyApp.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@Entity
@Table(name = "COUNTRIES")
@NamedQueries({
		@NamedQuery(name = "Country.getCountriesByName", query = "from Country where countryName = :countryName"),
		@NamedQuery(name = "Country.getAllCountries", query = "from Country"),
		@NamedQuery(name = "Country.getCountriesByMinValueOfCurrencies", query = "from Country c where size(c.currencies) >= :minValueOfCurrencies") })
public class Country {

	@Id
	@Column(name = "CURRENCY_ID")
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long countryId;

	@Column(name = "COUNTRY_CODE")
	private String countryName;

	@OneToMany(cascade = { CascadeType.ALL })
	// , fetch = FetchType.EAGER
	@Fetch(FetchMode.JOIN)
	@NotFound(action = NotFoundAction.IGNORE)
	@JoinTable(name = "JOIN_CURRENCY_COUNTRY", joinColumns = { @JoinColumn(name = "currencyId") }, inverseJoinColumns = { @JoinColumn(name = "countryId") })
	private final List<Currency> currencies = new ArrayList<Currency>();

	public Country() {
	}

	public Country(String countryName) {
		this.countryName = countryName;
	}

	public long getId() {
		return countryId;
	}

	public void setId(long id) {
		this.countryId = id;
	}

	public String getCountryName() {
		return countryName;
	}

	public boolean addCurrency(Currency value) {
		return currencies.add(value);
	}

	public Currency[] getCurrencies() {
		return currencies.toArray(new Currency[currencies.size()]);
	}

	public int getCurrencySize() {
		return currencies.size();
	}

	public void changeName(String name) {
		this.countryName = name;
	}

	@Override
	public int hashCode() {
		return countryName.hashCode();
	}

	@Override
	public boolean equals(Object o) {
		return countryName.equals(o);
	}
}
